﻿using Mengsk.ProxyDelivery.Domain;
using Mengsk.ProxyDelivery.HTTPHelpers;
using Mengsk.ProxyDelivery.Print.Service;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Windows;
using System.Xml.Linq;

namespace Mengsk.ProxyDelivery.App.Service.DeliveryService
{
    public class DeliveryQueryService
    {
        const string APIURL = "http://www.kuaidi100.com/query";
        const string APPCODE = "e652b80bcaf24ff5";
        const string FORMAT = "2";
        private static Dictionary<string, string> companyCodes = new Dictionary<string, string>();
        private static Dictionary<string, string> para = new Dictionary<string, string>();
        DataContractJsonSerializer sizeSer = new DataContractJsonSerializer(typeof(DeliveryResult));
        Random r = new Random(456456);

        static DeliveryQueryService()
        {
            companyCodes["百世汇通"] = "huitongkuaidi";
            companyCodes["EMS"] = "ems";
            companyCodes["EMS经济快递"] = "ems";
            companyCodes["天天快递"] = "tiantian";
            companyCodes["邮政小包"] = "youzhengguonei";
            companyCodes["宅急送"] = "zhaijisong";
            companyCodes["韵达快递"] = "yunda";
            companyCodes["顺丰速运"] = "shunfeng";
            companyCodes["圆通速递"] = "yuantong";
            companyCodes["全峰快递"] = "quanfengkuaidi";
            companyCodes["优速快递"] = "youshuwuliu";
            companyCodes["中通速递"] = "zhongtong";
            companyCodes["申通快递"] = "shentong";
            companyCodes["国通快递"] = "guotongkuaidi";
            companyCodes["快捷快递"] = "kuaijiesudi";
            companyCodes["速尔快递"] = "suer";
            companyCodes["龙邦物流"] = "longbanwuliu";
            companyCodes["德邦物流"] = "debangwuliu";
            para["key"] = APPCODE;
        }

        public Domain.DeliveryTransation Query(String company, string number)
        {
            if (companyCodes.ContainsKey(company) == false)
            {
                throw new Exception("未能找到对应的快递公司");
            }

            String code = companyCodes[company];
            para["type"] = code;
            para["postid"] = number;
            para["temp"] = "0." + r.Next() + "" + r.Next();
            String content = MSHttpRestful.DoWithRetry(() => MSHttpRestful.DoGet(APIURL, Encoding.UTF8, null, null, para), 5);
            Byte[] bytes = Encoding.UTF8.GetBytes(content);
            var ret = this.sizeSer.ReadObject(new MemoryStream(bytes, false)) as DeliveryResult;

            var item = new Domain.DeliveryTransation();
            item.IsSigned = ret.ischeck == "1" ? true : false;
            if (ret.message.ToUpper().Equals("OK") == false)
            {
                throw new Exception(ret.message);
            }
            item.Items = new List<Domain.DeilveryTransationItem>();
            foreach (var o in ret.data)
            {
                item.Items.Add(new Domain.DeilveryTransationItem { Time = DateTime.Parse(o.ftime), Description = o.context });
            }

            return item;
        }

        public bool CheckAddress(string company, string number, string address)
        {
            var ret = this.Query(company, number);
            if (ret.IsSigned == false)
            {
                //throw new Exception("快递单号没有被签收，不能处理");
            }

            if (ret.Items.Count < 1)
            {
                throw new Exception("快递单号没有查询到物流信息");
            }

            var city = AddressService.ParseCity(address);
            var region = AddressService.ParseRegion(address);

            if (city == null)
            {
                MessageBox.Show("未找到发货址中的市");
                return false;
            }

            if (address.Length > 15)
            {
                address = address.Substring(0, 15);
            }

            List<string> descriptions = new List<string>();


            for (int i = 0; i < 2 && i < ret.Items.Count; i++)
            {
                string source = ret.Items[ret.Items.Count - 1 - i].Description;
                if (descriptions.Contains(source) == false)
                {
                    descriptions.Add(source);
                }
            }

            string regionName = region != null ? AddressService.GetCityShortName(region.Name) : "";
            string cityName = AddressService.GetCityShortName(city.Name);
            foreach (string source in descriptions)
            {
                if (string.IsNullOrWhiteSpace(regionName) == false)
                {
                    if (source.Contains(regionName))
                    {
                        return true;
                    }
                }

                if (source.Contains(cityName))
                {
                    return true;
                }
            }

            return false;
        }
    }

    public class DeliveryItem
    {
        public String time;
        public string location;
        public string context;
        public string ftime;
    }

    public class DeliveryResult
    {
        public string message;
        public string nu;
        public string companytype;
        public string ischeck;
        public string com;
        public string updatetime;
        public string status;
        public string condition;
        public string codenumber;

        public List<DeliveryItem> data;
    }
}
